package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/mark3labs/mcp-go/client"
	"github.com/mark3labs/mcp-go/mcp"
)

func main() {
	mcpClient, err := client.NewStdioMCPClient("./server/server", []string{})
	if err != nil {
		panic(err)
	}
	defer mcpClient.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	initRequest := mcp.InitializeRequest{}
	initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
	initRequest.Params.ClientInfo = mcp.Implementation{
		Name:    "Client Demo",
		Version: "1.0.0",
	}

	initResult, err := mcpClient.Initialize(ctx, initRequest)
	if err != nil {
		panic(err)
	}
	fmt.Printf("初始化成功，服务器信息: %s %s\n", initResult.ServerInfo.Name, initResult.ServerInfo.Version)

	// 调用工具
	toolRequest := mcp.CallToolRequest{
		Request: mcp.Request{
			Method: "tools/call",
		},
	}
	toolRequest.Params.Name = "calculate"
	toolRequest.Params.Arguments = map[string]any{
		"operation": "divide",
		"x":         22,
		"y":         4,
	}

	result, err := mcpClient.CallTool(ctx, toolRequest)
	if err != nil {
		panic(err)
	}
	fmt.Println("调用工具结果:", result.Content[0].(mcp.TextContent).Text)

	// 列出资源
	listRequest := mcp.ListResourcesRequest{}
	listResult, err := mcpClient.ListResources(ctx, listRequest)
	if err != nil {
		log.Fatalf("Failed to list resources: %v", err)
	}

	fmt.Printf("Number of resources: %d\n", len(listResult.Resources))

	// 读取资源
	if len(listResult.Resources) > 0 {
		readRequest := mcp.ReadResourceRequest{}
		readRequest.Params.URI = listResult.Resources[0].URI

		readResult, err := mcpClient.ReadResource(ctx, readRequest)
		if err != nil {
			log.Fatalf("Failed to read resource: %v", err)
		}

		fmt.Printf("Number of content items: %d\n", len(readResult.Contents))
		for _, content := range readResult.Contents {
			if textContent, ok := content.(mcp.TextResourceContents); ok {
				fmt.Printf("Resource content: %s\n", textContent.Text)
			}
		}
	}
}
